package cn.yanglq.Rss.web.controller.retrievepwd;

import cn.yanglq.Rss.web.common.vo.ApiResult;
import cn.yanglq.Rss.web.controller.BaseController;
import cn.yanglq.Rss.web.dao.UserMapper;
import cn.yanglq.Rss.web.model.RandomCode;
import cn.yanglq.Rss.web.model.SysParamConstData;
import cn.yanglq.Rss.web.model.User;
import cn.yanglq.Rss.web.service.MailService;
import cn.yanglq.Rss.web.service.RandomCodeService;
import cn.yanglq.Rss.web.service.SysParamService;
import cn.yanglq.Rss.web.service.UserService;
import cn.yanglq.Rss.web.util.SmsIdentifyingCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.Objects;

/**
 * Created by yanglq on 2018/1/19.
 */
@Controller
@RequestMapping("/retrievepwd")
public class RetrievePwdController extends BaseController {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RandomCodeService randomCodeService;
    @Autowired
    private SysParamService sysParamService;
    @Autowired
    private MailService mailService;
    @Autowired
    private UserService userService;

    private static final String SMS_TEMP = "您的邮箱验证码: ${code}。请${validmin}分钟内使用，仅限本次有效。";

    @RequestMapping
    public String retrievepwdPage() {

        return "/retrievepwd/retrievepage";
    }


    @RequestMapping(value = "/validLoginId")
    @ResponseBody
    public ApiResult validLoginId(
            @RequestParam(value = "loginId", required = true) String loginId) {
        ApiResult result = new ApiResult();
        User user = userMapper.selectByPrimaryKey(loginId);
        if (user != null) {
            result.setErrorcode(0);
            result.setSuccess(true);
            result.setMessage("验证通过！");
        } else {
            result.setErrorcode(-1);
            result.setSuccess(false);
            result.setMessage("请输入正确的用户名");
        }

        return result;
    }

    /**
     * 用户修改密码时发送验证码至邮箱，并记录到数据库
     *
     * @param regEmail
     * @return
     */
    @RequestMapping(value = "/identifyingCode")
    @ResponseBody
    public ApiResult identifyingCode(
            @RequestParam(value = "regEmail", required = true) String regEmail) {

        ApiResult result = new ApiResult();

        //2次发送间隔时间
        int intervaltime = sysParamService.findSysParam(
                SysParamConstData.SYS_SENDSMS_TIME_INTERVAL);

        RandomCode emaillog = randomCodeService
                .getRandomCode(regEmail);
        if (emaillog != null) {
            long time = (System.currentTimeMillis() - emaillog.getCreatetime()
                    .getTime()) / 1000;

            if (time < intervaltime) {
                result.setErrorcode(3);
                result.setSuccess(false);
                result.setMessage("获取验证码频率过快，请稍后再试！");
                return result;
            }

            if (time < emaillog.getValidtime()) {
                emaillog.setStatus((short) 1);
                randomCodeService.updateCodeRecord(emaillog);
            }
        }
        // TODO 这里要保存短信记录到数据库，生成创建时间以便判断验证码有效性，还有发送邮件
        String code = SmsIdentifyingCode.create(6);
        int validMin = sysParamService.findSysParam(SysParamConstData.SYS_PASSWDSMS_VALIDMIN);
        int validTime = validMin * 60;
        String sms = SMS_TEMP.replace("${code}", code).replace("${validmin}",
                validMin + "");

        User user = userService.selectUserInfoByEmail(regEmail);

        RandomCode log = new RandomCode();
        log.setCreatetime(new Date());
        log.setCreatetime(new Date());
        if (user != null) {
            log.setUserid(user.getUserid());
        }
        log.setCode(code);
        log.setMsg(sms);
        log.setValidtime(validTime);
        log.setStatus((short) 0);

        int n;
        if (mailService.sendEmail(regEmail, sms)) {
            n = randomCodeService.saveCodeRecord(log);
            if (n == 0) {
                result.setErrorcode(0);
                result.setSuccess(true);
                result.setMessage("验证码发送成功！");
            } else {
                result.setErrorcode(1);
                result.setSuccess(false);
                result.setMessage("验证码发送失败！");
            }
        } else {
            result.setErrorcode(1);
            result.setSuccess(false);
            result.setMessage("验证码发送失败！");
        }

        return result;
    }

    @RequestMapping(value = "/validSmsCode")
    @ResponseBody
    public ApiResult validSmsCode(
            @RequestParam(value = "regEmail", required = true) String regEmail,
            @RequestParam(value = "emailCode", required = true) String emailCode) {

        ApiResult result = new ApiResult();
        RandomCode log = randomCodeService
                .getRandomCode(regEmail);
        if (log == null) {
            result.setErrorcode(-1);
            result.setSuccess(false);
            result.setMessage("找不到发送的验证码记录！");
            return result;
        }
        long time = (System.currentTimeMillis() - log.getCreatetime().getTime()) / 1000;
        if (log.getCode().equals(emailCode) && time < log.getValidtime()) {
            randomCodeService.updateCodeRecord(log);

            result.setErrorcode(0);
            result.setSuccess(true);
            result.setMessage("验证通过！");
        } else {

            if (time < log.getValidtime()) {
                log.setStatus((short) 2);
                randomCodeService.updateCodeRecord(log);

                result.setErrorcode(1);
                result.setSuccess(false);
                result.setMessage("验证码已过有效期！");
            } else {
                result.setErrorcode(2);
                result.setSuccess(false);
                result.setMessage("验证码错误！");
            }

        }

        return result;
    }


    @RequestMapping(value = "/validRegEmail")
    @ResponseBody
    public ApiResult validRegEmail(
            @RequestParam(value = "regEmail", required = true) String regEmail,
            @RequestParam(value = "loginId", required = true) String loginId) {
        ApiResult result = new ApiResult();
        User user = userMapper.selectByPrimaryKey(loginId);
        if (Objects.equals(user.getEmail(), regEmail)) {
            result.setErrorcode(0);
            result.setSuccess(true);
            result.setMessage("验证通过！");
        } else {
            result.setErrorcode(-1);
            result.setSuccess(false);
            result.setMessage("请输入正确的注册邮箱");
        }

        return result;
    }


    @RequestMapping(value = "/resetPasswd")
    @ResponseBody
    public ApiResult resetPasswd(
            @RequestParam(value = "loginId", required = true) String loginId,
            @RequestParam(value = "asspwd", required = true) String passwd) {

        ApiResult result = new ApiResult();
        User user = userService.selectUserByUserId(loginId);
        if (user != null) {
            user.setPasswd(passwd);
            userMapper.updateByPrimaryKey(user);
            result.setErrorcode(0);
            result.setSuccess(true);
            result.setMessage("修改成功！");
            return result;
        }
        result.setErrorcode(1);
        result.setSuccess(false);
        result.setMessage("修改失败！");
        return result;
    }
}
